﻿using OA.BLL;

using OA.Core;
using OA.Core.Helper;
using OA.Model;
using OA.Model.View;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

using Z.EntityFramework.Plus;
using Microsoft.Extensions.Caching.Memory;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using OA.Web.Attribute;
using Microsoft.AspNetCore.Mvc;
using OA.Model.Form;
using OA.Model.DB;
using OA.Core.EF;
using X.PagedList;
using OA.Model.Mapper;
using OA.Core.DataAccessHelper;
using OA.Model.Result;
using OA.Core.Oss;

namespace OA.Web.Areas.Member.Controllers
{
    public class HomeController : BaseMemberController
    {
        private IMemoryCache _cache;
        private ICookie _cookie;
        public HomeController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
        }


        public IActionResult Desk()
        {
            return View();
        }


        public IActionResult GetProductCategory()
        {
            var productCategory = this.dbContextFactory.DbContext.ProductCategory.Select(m => new {
                i = m.ID,
                p = m.ParentID,
                n = m.Name
            }).ToList();

            
            ViewBag.ProductCategory = JsonConvert.SerializeObject(productCategory);
           
            return View();
        }
        


        [MyActionFilter("000000", "后台首页", "后台首页", false, "iconindex")]
        public IActionResult Index()
        {
            ViewBag.Notices = this.dbContextFactory.DbContext.Notice
                .Where(m=>m.Type== "公司公告")
                .OrderByDescending(m => m.ID).Take(3).Select(SimpleNotice.Map).ToList();

            #region 我的审批单据
            var currentCustomFormCodes = this.CurrentPermissionCodes.Where(m => m.StartsWith("002")&&m.Length==9).Select(m=>m.Substring(6)).ToList();
            var allCustomForm = this.dbContextFactory.DbContext.CustomForm.ToList();
            List<CustomForm> myCustomForm = new List<CustomForm>();
            foreach (var item in allCustomForm)
            {
                if(currentCustomFormCodes.Contains(item.ID.ToString("D3")))
                {
                    myCustomForm.Add(item);
                }
            }
            ViewBag.MyCustomForm = myCustomForm;

            #endregion

            #region 我的待办

            ViewBag.WaitForHandling = this.dbContextFactory.DbContext.VWaitForHandling.Where(m => m.RealEmpID == EmpID).OrderBy(m => m.ID).Skip(0).Take(5).ToList();

            #endregion

            #region 我的主办

            ViewBag.Launched = this.dbContextFactory.DbContext.Approval.Where(m => m.SponsorEmpID == EmpID && m.Status >= 1).OrderBy(m => m.ID).Skip(0).Take(5).ToList();

            #endregion

            #region 我的收件箱
            Expression<Func<Mailbox, bool>> where3 = m => m.ToEmpID == Info.EmpID;
            ViewBag.Inbox = this.dbContextFactory.DbContext.Mailbox.Where(where3).Take(5).ToList();

            #endregion


            return View( );
        }


        [MyActionFilter("000001", "通讯录", "后台首页", true, "iconbumen2")]
        public IActionResult AddressBooks(string keywrod, int p = 1, int size = 20)
        {
            return View();        
        }


        [MyActionFilter("000001", "通讯录", "后台首页", false, "")]
        public IActionResult AddressBooksData(string keywrod, int page = 1, int limit = 20)
        {
            if (string.IsNullOrWhiteSpace(keywrod))
            {
                var list = this.dbContextFactory.DbContext.VEmployeePosition.Where(m => m.Status != -1).OrderBy(m => m.EmpID).DistinctBy(m => m.EmpID).ToPagedList(page, limit);
                var result = new
                {
                    code = "0",
                    msg = "",
                    count = list.TotalItemCount,
                    data = list
                };
                return Json(result);
            }
            else
            {
                var list = this.dbContextFactory.DbContext.VEmployeePosition.Where(m => m.Status != -1 && m.EmpID == keywrod || m.EmpName.Contains(keywrod)).OrderBy(m => m.EmpID).DistinctBy(m => m.EmpID).ToPagedList(page, limit);
                var result = new
                {
                    code = "0",
                    msg = "",
                    count = list.TotalItemCount,
                    data = list
                };
                return Json(result);
            }
        }


        [HttpGet]
        public IActionResult UpdatePassword()
        {
            return View(new UpdatePasswordForm());
        }

        [HttpPost]
        public IActionResult UpdatePassword(UpdatePasswordForm model)
        {
            if (model.NewPassWord != model.NewPassWord2)
            {
                ViewBag.Msg = "新密码与确认密码不一致!";
                return View();
            }
            Employee infoUser = this.GetInfo<Employee>(this.Info.ID);
            if (infoUser == null)
            {
                ViewBag.Msg = "非法的操作!";
                return View();
            }
            string md5PassWord = (infoUser.EmpID.ToLower()+model.OldPassword).ToMd5String();
            if (infoUser.Password != md5PassWord)
            {
                ViewBag.Msg = "原始密码错误!";
                return View();
            }
            string md5PassWord2 = (infoUser.EmpID.ToLower() + model.NewPassWord).ToMd5String();
            Employee updateUser = new Employee();
            updateUser.Password = md5PassWord2;
            this.Update<Employee>(infoUser, updateUser, new string[] { "Password" });             
            return FinshOther("密码更新成功");
        }

        [HttpGet]
        public IActionResult Conduct(int id)
        {
            ApprovalItem infoApprovalItem = this.GetInfo<ApprovalItem>(id);
            if (infoApprovalItem == null)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到该审批单据");
            }
            if (infoApprovalItem.RealEmpID != Info.EmpID)
            {
                return Redirect("/Member/Tips/Index?msg=您没有该单据的审批权限");
            }

            Approval infoApproval= this.GetInfo<Approval>(infoApprovalItem.ApprovalID);
            if (infoApproval == null)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到该审批单据");
            }

            Voucher infoVoucher = CVoucher.GetVoucherByID(infoApproval.CustomID, infoApproval.FormID);
            if (infoVoucher == null)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到原始单据，请联系管理员");
            }

            CustomForm customForm = this.GetInfo<CustomForm>(infoVoucher.CustomFormID);

            List<ApprovalNode> nodes = JsonHelper.DeserializeList<ApprovalNode>(infoVoucher.ApprovalNodeContent);
            if(nodes==null)
            {
                return Redirect("/Member/Tips/Index?msg=数据错误，请联系管理员");
            }

            ApprovalNode infoProcessPoint = new ApprovalNode();
            if(customForm.IsCustomProcess)
            {
                var customProcessNodes=JsonHelper.DeserializeList<CustomProcessNode>(infoVoucher.TreeContent);
                var customProcessNode = customProcessNodes.Where(m => m.PositionID == infoApprovalItem.PositionID).FirstOrDefault();
                infoProcessPoint.DepartmentID = customProcessNode.DepartmentID;
                infoProcessPoint.PositionID = customProcessNode.PositionID;
                infoProcessPoint.EmpID = customProcessNode.EmpID;
            }
            else
            {
                infoProcessPoint = nodes.Where(m=>m.PositionID== infoApprovalItem.PositionID&& m.Step== infoApprovalItem.Step).FirstOrDefault();
            }
           
            if (infoProcessPoint == null)
            {
                return Redirect("/Member/Tips/Index?msg=当前流程与处理流程冲突，可能是后台处理流程发生了变化，请联系管理员");
            }

            if (string.IsNullOrWhiteSpace(infoProcessPoint.EnableEditableFields)) { infoProcessPoint.EnableEditableFields = string.Empty; }

            if (infoApprovalItem.Status != 0) { infoProcessPoint.EnableEditableFields = ""; }

            ViewBag.EnableEditableFields = infoProcessPoint.EnableEditableFields.Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries).ToList();


            if (string.IsNullOrWhiteSpace(infoProcessPoint.PrivacyFields)) { infoProcessPoint.PrivacyFields = string.Empty; }

            ViewBag.PrivacyFields = infoProcessPoint.PrivacyFields.Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries).ToList();



           
            CustomFormExtendInfo extendInfo = null;
            if (!string.IsNullOrWhiteSpace(infoVoucher.CustomFormContent))
            {
                extendInfo = JsonHelper.DeserializeObj<CustomFormExtendInfo>(infoVoucher.CustomFormContent);
            }
            else if (!string.IsNullOrWhiteSpace(customForm.ExtendField))
            {
                extendInfo = JsonHelper.DeserializeObj<CustomFormExtendInfo>(customForm.ExtendField);
            }

            if (extendInfo == null)
            {
                extendInfo = new CustomFormExtendInfo();
            }

            List<ExtendField> extendFields = null;
            if (!string.IsNullOrWhiteSpace(infoVoucher.CustomFormContent))
            {
                extendFields = JsonHelper.DeserializeList<ExtendField>(infoVoucher.CustomFormContent);
            }

            if (extendFields == null)
            {
                extendFields = new List<ExtendField>();
            }


            ViewBag.CustomForm = customForm;
            ViewBag.ExtendFields = extendFields;//表单结构
            CVoucher objVoucher = new CVoucher();
            objVoucher.Map(infoVoucher, customForm, _cache);
            ViewBag.InfoApproval = infoApproval;
            ViewBag.InfoApprovalItem = infoApprovalItem;
            var approvalItems = this.dbContextFactory.DbContext.ApprovalItem.Where(m => m.ApprovalID == infoApproval.ID).OrderBy(m => m.ID).ToList();

            CacheHelper cacheHelper = new CacheHelper(_cache);
            List<Department> listDepartment = cacheHelper.GetDepartments();
            List<Position> listPosition = cacheHelper.GetPositions();
            List<Employee> listEmployee = cacheHelper.GetEmployees();
            List<VEmployeePosition> listEmployeePosition = cacheHelper.GetVEmployeePositions();

            var baseConfig = cacheHelper.GetConfig<BaseConfig>();

            CApproval approval = new CApproval(_cache);
            ApprovalResult approvalResult = approval.GetApprovalResult(listDepartment, listPosition, listEmployee, listEmployeePosition, customForm, infoVoucher, approvalItems, baseConfig.PositionLevel);

            ViewBag.ApprovalResult = approvalResult;

            return View(infoVoucher);

        }

        [HttpPost]
        public IActionResult Conduct(int id, int status, string explain, Voucher info, Dictionary<string, string> dicExtend)
        {
            ApprovalItem infoApprovalItem = this.GetInfo<ApprovalItem>(id);
            if (infoApprovalItem == null)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到该处理项");
            }
            if (infoApprovalItem.RealEmpID != Info.EmpID)
            {
                return Redirect("/Member/Tips/Index?msg=您没有该单据的处理权限");
            }

           
            Approval infoApproval = this.GetInfo<Approval>(infoApprovalItem.ApprovalID);
            if (infoApproval == null)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到该处理项");
            }

            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, infoApproval.CustomID);
            Voucher infoVoucher = dal.GetByID<Voucher>(infoApproval.FormID);
            
            if (infoVoucher == null)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到原始单据，请联系管理员");
            }


            CustomForm customForm= this.GetInfo<CustomForm>(infoApproval.CustomID);

            if (status == 5)//需沟通
            {
                var dbContext = dal.GetDbContext();
                using (var trn = dbContext.Database.BeginTransaction())
                {
                    try
                    {
                        if (string.IsNullOrWhiteSpace(infoApproval.NeedExplainEmpID))
                        {
                            infoApproval.NeedExplainEmpID = infoApprovalItem.RealEmpName;
                        }
                        else
                        {
                            infoApproval.NeedExplainEmpID += "," + infoApprovalItem.RealEmpName;
                        }
                        infoApprovalItem.Status = 1;
                        infoApprovalItem.Explain = explain;
                        infoApprovalItem.ApprovalTime = DateTime.Now;
                        dal.Update<Approval>(infoApproval);
                        dal.Update<ApprovalItem>(infoApprovalItem);
                        dal.Save();
                        trn.Commit();
                        return Json(new BaseResult() { State = 200 });
                    }
                    catch(Exception ex)
                    {
                        trn.Rollback();
                        BaseResult result = new BaseResult();
                        result.State = 400;
                        result.Msg = $"审批失败,系统异常！请稍后重试";
                        return Json(result);
                    }
                    
                }
            }
            else if (status == 6)//不同意
            {
                var dbContext = dal.GetDbContext();
                using (var trn = dbContext.Database.BeginTransaction())
                {
                    DateTime now = DateTime.Now;
                    try
                    {
                        infoApproval.Explain = explain;
                        infoApproval.NeedExplainEmpID = "";
                        infoApproval.Suspense = "";
                        infoApproval.Status = 3;
                        infoApproval.FinishTime = now;
                        dbContext.Set<Approval>().Update(infoApproval);
                        infoApprovalItem.Status = 4;
                        infoApprovalItem.Explain = explain;
                        infoApprovalItem.ApprovalTime = now;
                        dbContext.Set<ApprovalItem>().Update(infoApprovalItem);
                        dal.Save();
                        trn.Commit();
                        return Json(new BaseResult() { State = 200 });
                    }
                    catch (Exception ex)
                    {
                        trn.Rollback();
                        BaseResult result = new BaseResult();
                        result.State = 400;
                        result.Msg = $"审批失败,系统异常！请稍后重试";
                        return Json(result);
                    }
                }
            }
            else if(status==7)//转移
            {
                return View();
            }
            else //同意 status=4
            {
                infoApprovalItem.Explain = explain;
                CApproval objApproval = new CApproval(_cache);
                return Json(objApproval.Conduct(dal,0, Info, infoApproval, infoApprovalItem, customForm, infoVoucher, dicExtend));
            }
           
        }


        [HttpPost]
        public IActionResult Remove(int id, int positionID, string explain)
        {
            BaseResult result = new BaseResult();
            ApprovalItem infoApprovalItem = this.dbContextFactory.DbContext.ApprovalItem.Where(m => m.ID == id).FirstOrDefault();
            if (infoApprovalItem == null || infoApprovalItem.RealEmpID != Info.EmpID)
            {
                result.State = 400;
                result.Msg = "没有找到审批项";
                return Json(result);
            }
            if (infoApprovalItem.Status != 0)
            {
                result.State = 400;
                result.Msg = "已经审批的单据不能重复审批";
                return Json(result);
            }

            Approval infoApproval = this.GetInfo<Approval>(infoApprovalItem.ApprovalID);
            if (infoApproval == null)
            {
                result.State = 400;
                result.Msg = "没有找到该处理项";
                return Json(result);
            }

            Voucher infoVoucher = CVoucher.GetVoucherByID(infoApproval.CustomID, infoApproval.FormID);
            if (infoVoucher == null)
            {
                result.State = 400;
                result.Msg = "没有找到原始单据";
                return Json(result);
            }
            List<ApprovalItem> listApprovalItem = this.dbContextFactory.DbContext.ApprovalItem.Where(m => m.ApprovalID == infoApprovalItem.ApprovalID && m.Status == 0).ToList();
            ApprovalItem nextApprovalItem = listApprovalItem.Where(m => m.PositionID == positionID).FirstOrDefault();
            if (nextApprovalItem == null)
            {
                result.State = 400;
                result.Msg = "没有找到新的审批人";
                return Json(result);
            }

            ApprovalItem updateApprovalItem = new ApprovalItem();
            updateApprovalItem.Status = 7;
            updateApprovalItem.ApprovalTime = DateTime.Now;
            updateApprovalItem.Explain = explain;

            ApprovalItem newApprovalItem = JsonHelper.DeserializeObj<ApprovalItem>(JsonConvert.SerializeObject(nextApprovalItem));
            newApprovalItem.ID = 0;
            newApprovalItem.Status = 0;
            newApprovalItem.Explain = "";

             

            using (var trn=this.dbContextFactory.DbContext.Database.BeginTransaction())
            {
                try
                {
                    this.dbContextFactory.AddInfo<ApprovalItem>(newApprovalItem);
                    this.dbContextFactory.Update<ApprovalItem>(infoApprovalItem, updateApprovalItem,new string[] { "Status", "ApprovalTime", "Explain" });
                    
                    trn.Commit();
                    return Json(result);
                }
                catch(Exception ex)
                {
                    trn.Rollback();
                    result.State = 400;
                    result.Msg = "数据库操作异常!请联系管理员";
                    return Json(result);
                }
            }

        }


        [HttpGet]
        public IActionResult ChangeHead()
        {
            ViewBag.Avatar = Info.Pic+ "?x-oss-process=image/resize,m_fill,w_200,h_200,limit_0/auto-orient,0/quality,q_90";
            return View();
        }


        [HttpGet]
        public IActionResult UpdateHead(string url)
        {
            try
            {
                Employee updateEmployee = new Employee { Pic = url };
                this.UpdateByID<Employee>(Info.ID, updateEmployee, new string[] { "Pic" });
                _cookie.SetCookies(CookieHelper.Avatar_User, url, 1440);
                CacheHelper cacheHelper = new CacheHelper(_cache);
                cacheHelper.ClearEmployeesCache();
                return Json(new { State = 200, Message = "" });
            }
            catch (Exception ex)
            {                
                return Json(new { State = 400, Message = "头像上传失败" });
            }

        }

        [HttpGet]
        public IActionResult Logout()
        {
            _cookie.DeleteCookies(CookieHelper.UserID);
            _cookie.DeleteCookies(CookieHelper.DisplayName);
            return Redirect("/");
        }
        
        [HttpGet]
        public IActionResult ShowIM()
        {
            var departments = this.dbContextFactory.DbContext.Department.Select(m => new SimpleDepartment2 { ID = m.ID, Name = m.Name, ParentDepartmentID = m.ParentDepartmentID }).ToList();
            var employeePositions = this.dbContextFactory.DbContext.Database.SqlQuery<Employee8>("select * from  EmployeeTree").ToList();
            List<IMInfo> list = new List<IMInfo>();

            List<SimpleDepartment2> level_1 = departments.Where(m => m.ParentDepartmentID == 0).ToList();
            List<SimpleDepartment2> level_2 = new List<SimpleDepartment2>();
            List<SimpleDepartment2> level_3 = new List<SimpleDepartment2>();
            
            foreach (SimpleDepartment2 department in level_1)
            {
                var employees = employeePositions.Where(m => m.DepartmentID == department.ID).ToList();
                if (employees.Count > 0)
                {
                    IMInfo item = new IMInfo();
                    item.Name = department.Name;
                    item.ListUser = new List<UserInfo>();
                    foreach (Employee8 employee in employees)
                    {
                        UserInfo itemInfo = new UserInfo();
                        itemInfo.Honor = employee.Honor;
                        itemInfo.Name = employee.EmpName;
                        itemInfo.EmpID = employee.EmpID;
                        itemInfo.Telephone = employee.Telephone;
                        item.ListUser.Add(itemInfo);
                    }
                    list.Add(item);
                }
                var chilrenDepartment = departments.Where(m => m.ParentDepartmentID == department.ID).ToList();
                level_2 = level_2.Union(chilrenDepartment).ToList();
            }

            foreach (SimpleDepartment2 department in level_2)
            {
                var employees = employeePositions.Where(m => m.DepartmentID == department.ID).ToList();
                if (employees.Count > 0)
                {
                    IMInfo item = new IMInfo();
                    item.Name = department.Name;
                    item.ListUser = new List<UserInfo>();
                    foreach (Employee8 employee in employees)
                    {
                        UserInfo itemInfo = new UserInfo();
                        itemInfo.Honor = employee.Honor;
                        itemInfo.Name = employee.EmpName;
                        itemInfo.EmpID = employee.EmpID;
                        itemInfo.Telephone = employee.Telephone;
                        item.ListUser.Add(itemInfo);
                    }
                    list.Add(item);
                }
                var chilrenDepartment = departments.Where(m => m.ParentDepartmentID == department.ID).ToList();
                level_3 = level_3.Union(chilrenDepartment).ToList();
            }

            foreach (SimpleDepartment2 department in level_3)
            {
                IMInfo item = new IMInfo();
                item.Name = department.Name;
                item.ListUser = new List<UserInfo>();
                GetAllEmployee(department.ID, item, employeePositions, departments);
                list.Add(item);
            }

            return View(list);
        }

        public void GetAllEmployee(int departmentID,IMInfo item,List<Employee8> employeePositions, List<SimpleDepartment2> departments)
        {
            var employees = employeePositions.Where(m => m.DepartmentID == departmentID).ToList();
            if (employees.Count > 0)
            {
                foreach (Employee8 employee in employees)
                {
                    UserInfo itemInfo = new UserInfo();
                    itemInfo.Honor = employee.Honor;
                    itemInfo.Name = employee.EmpName;
                    itemInfo.EmpID = employee.EmpID;
                    itemInfo.Telephone = employee.Telephone;
                    item.ListUser.Add(itemInfo);
                }
            }
            var chilrenDepartment = departments.Where(m => m.ParentDepartmentID == departmentID).ToList();
            foreach (SimpleDepartment2 department in chilrenDepartment)
            {
                GetAllEmployee(department.ID, item, employeePositions, departments);
            }
        }

        public IActionResult ShowEmployee(string empID)
        {
            var info=this.dbContextFactory.DbContext.Employee.Where(m => m.EmpID == empID).FirstOrDefault();
            return View(info);
        }

        public IActionResult ShowInfo(string msg)
        {
            ViewBag.Msg = msg;
            return View();
        }


        [HttpGet]
        public IActionResult GetReferences(string param, string keywords)
        {
            try
            {
                string itemStr = param.FromBase62<string>();
                int customID = 0;
                Expression<Func<Voucher, bool>> where = m => m.Status == 4;
                if (Int32.TryParse(itemStr, out customID))
                {
                    string empID = base.EmpID;
                    Func<ReferencesVoucher, int> order = m => m.ID;
                    VoucherMapper voucherMapper = new VoucherMapper();
                    var dal = DataAccessor.Create<VoucherDbContext>();
                    dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customID);
                    where = m => m.Title.Contains(keywords) && m.Sponsor == empID;
                    var result = dal.GetPageList<Voucher, ReferencesVoucher, int>(10, 1, where, ReferencesVoucher.ReferencesMap, order, false);
                    return Json(new
                    {
                        content = result.Select(m => new SimpleReferences
                        {
                            CustomID = customID,
                            Title = m.Title,
                            No = m.No,
                            FormID = m.FormID,
                            JsonInfo = JsonHelper.SerializeObject(new
                            {
                                CustomID = customID,
                                Title = m.Title,
                                No = m.No,
                                FormID = m.FormID,
                            }).ToBase64()
                        }).ToList(),
                        type = "success",
                        code = 0
                    }); ;
                }
                else
                {
                    return Json(new { type = "非法的参数", code = 201 });
                }
            }
            catch (Exception ex)
            {
                return Json(new { type = ex.ToString(), code = 201 });
            }

        }


        public IActionResult PermissionDenied(string url)
        {
            return View();
        }



        [HttpGet]
        public IActionResult GetDepartmentAndPosition()
        {
            var departments = this.dbContextFactory.DbContext.Department.Where(m => m.Status != -1).Select(m => new {
                i = m.ID,
                p = m.ParentDepartmentID,
                n = m.Name
            }).ToList();

            var positions = this.dbContextFactory.DbContext.Position.Where(m => m.Status != -1).Select(m => new {
                i = m.ID,
                d = m.DepartmentID,
                n = m.Name
            }).ToList();

            var employeePositions = this.dbContextFactory.DbContext.VEmployeePosition.Select(m => new {
                p = m.PositionID,
                i =JsonHelper.ToBase64( new SimpleEmpInfo()
                {
                    EmpID = m.EmpID,
                    Name = m.EmpName,
                    DepartmentID=m.DepartmentID
                }),
                n = m.EmpName,
                d = m.DepartmentID
                }).ToList();

            ViewBag.Departments = JsonConvert.SerializeObject(departments);
            ViewBag.Positions = JsonConvert.SerializeObject(positions);
            ViewBag.EmployeePositions = JsonConvert.SerializeObject(employeePositions);
            return View();
        }

        [HttpGet]
        public IActionResult GetEmployees(string keywords)
        {
            Func<VEmployeePosition, bool> where = m => m.Status != -1;
            if (!string.IsNullOrWhiteSpace(keywords))
            {
                where = m => m.Status != -1 && (m.EmpID.Contains(keywords) || m.EmpName.Contains(keywords) || m.DepartmentName.Contains(keywords) || m.Name.Contains(keywords));
            }
            var employeePositions = this.dbContextFactory.DbContext.VEmployeePosition.Where(where).Select(m => new {
                p = m.PositionID,
                s = m.Name,
                i = m.EmpID,
                n = m.EmpName,
                d = m.DepartmentName,
                di=m.DepartmentID
            }).ToList();

            ViewBag.Employees = JsonConvert.SerializeObject(employeePositions);
            return Json(new { content = employeePositions, type = "success", code = 0 });
        }

        [HttpGet]
        public IActionResult GetEmployeeNoticeTree(int id)
        {
            var selects = this.dbContextFactory.DbContext.EmployeeNotice.Where(m => m.NoticeID == id).Select(m => m.EmpID).ToList();
            var departments = this.dbContextFactory.DbContext.Department.Select(m => new SimpleDepartment2 { ID = m.ID, Name = m.Name, ParentDepartmentID = m.ParentDepartmentID }).ToList();
            var employeePositions = this.dbContextFactory.DbContext.Database.SqlQuery<Employee8>("select * from  EmployeeTree").ToList();
            List<MyTree> list = new List<MyTree>();

            var topDepartment = departments.Where(m => m.ParentDepartmentID == 0).ToList();
            foreach (var department in topDepartment)
            {
                MyTree tree = new MyTree();
                tree.t = department.Name;
                tree.d = new List<MyTree>();
                tree.v = "";
                InintEmployeeTree(tree, department.ID, departments, employeePositions, selects);
                list.Add(tree);
            }
            return Json(list);
        }

        [HttpGet]
        public IActionResult GetEmployeeCustomFormTree(int id)
        {
            var selects = this.dbContextFactory.DbContext.EmployeeCustomForm.Where(m => m.CustomFormID == id).Select(m => m.EmpID).ToList();
            var departments = this.dbContextFactory.DbContext.Department.Select(m => new SimpleDepartment2 { ID = m.ID, Name = m.Name, ParentDepartmentID = m.ParentDepartmentID }).ToList();
            var employeePositions = this.dbContextFactory.DbContext.Database.SqlQuery<Employee8>("select * from  EmployeeTree").ToList();
            List<MyTree> list = new List<MyTree>();

            var topDepartment = departments.Where(m => m.ParentDepartmentID == 0).ToList();
            foreach (var department in topDepartment)
            {
                MyTree tree = new MyTree();
                tree.t = department.Name;
                tree.d = new List<MyTree>();
                tree.v = "";
                InintEmployeeTree(tree, department.ID, departments, employeePositions, selects);
                list.Add(tree);
            }
            return Json(list);
        }

        public void InintEmployeeTree(MyTree tree, int departmentID, List<SimpleDepartment2> listDepartment, List<Employee8> listEmployee, List<string> selects)
        {
            var employees = listEmployee.Where(m => m.DepartmentID == departmentID).ToList();
            foreach (Employee8 employee in employees)
            {
                MyTree employeePoint = new MyTree();
                employeePoint.t = employee.EmpName;
                employeePoint.v = employee.EmpID;
                if (selects.Contains(employee.EmpID))
                {
                    employeePoint.s = 1;
                }
                employeePoint.d = new List<MyTree>();
                tree.d.Add(employeePoint);
            }
            var children = listDepartment.Where(m => m.ParentDepartmentID == departmentID).ToList();
            foreach (var department in children)
            {
                MyTree departmentPoint = new MyTree();
                departmentPoint.t = department.Name;
                departmentPoint.v = "";
                departmentPoint.d = new List<MyTree>();
                InintEmployeeTree(departmentPoint, department.ID, listDepartment, listEmployee, selects);
                tree.d.Add(departmentPoint);
            }
        }

        [HttpGet]
        public IActionResult GetPositions(string keywords)
        {
            Func<MyPosition, bool> where = m => true;
            if (!string.IsNullOrWhiteSpace(keywords))
            {
                where = m => m.DepartmentName.Contains(keywords) || m.PositionName.Contains(keywords);
            }
            var positions = this.dbContextFactory.DbContext.Database.SqlQuery<MyPosition>("select * from  Position_Department").Where(where).Select(m => new {
                i = m.ID,
                n = m.PositionName,
                d = m.DepartmentID,
                m = m.DepartmentName
            }).ToList();

            return Json(new { content = positions, type = "success", code = 0 });
        }

        [HttpGet]
        public IActionResult GetDepartments(string keywords)
        {
            Func<Department, bool> where = m => true;
            if (!string.IsNullOrWhiteSpace(keywords))
            {
                where = m => m.Name.Contains(keywords);
            }
            var departments = this.dbContextFactory.DbContext.Department.Where(where).Select(m => new { i = m.ID, n = m.Name }).ToList();

            return Json(new { content = departments, type = "success", code = 0 });
        }


        [HttpGet]
        public IActionResult GetCustomer(string keywords)
        {
            var result = this.dbContextFactory.DbContext.RelatedCompany.Where(m => m.IsCustomer).Select(m=>new { m.ID,m.Name}).ToList();

            return Json(new
            {
                content = result.Select(m => new
                {
                    m.ID,
                    m.Name,
                    JsonInfo = JsonHelper.ToBase64(new
                    {
                        m.ID,
                        m.Name
                    })
                }).ToList(),
                type = "success",
                code = 0
            });
        }

        [HttpGet]
        public IActionResult GetRelatedCompany(string keywords)
        {
            var result = this.dbContextFactory.DbContext.RelatedCompany.Select(m => new { m.ID, m.Name }).ToList();

            return Json(new
            {
                content = result.Select(m => new
                {
                    m.ID,
                    m.Name,
                    JsonInfo = JsonHelper.ToBase64(new
                    {
                        m.ID,
                        m.Name
                    })
                }).ToList(),
                type = "success",
                code = 0
            });

        }



        [HttpGet]
        public IActionResult GetSupplier(string keywords)
        {
            var result = this.dbContextFactory.DbContext.RelatedCompany.Where(m=>m.IsSupplier).Select(m => new { m.ID, m.Name }).ToList();

            return Json(new
            {
                content = result.Select(m => new
                {
                    m.ID,
                    m.Name,
                    JsonInfo = JsonHelper.ToBase64(new
                    {
                        m.ID,
                        m.Name
                    })
                }).ToList(),
                type = "success",
                code = 0
            });

        }

        [HttpGet]
        public IActionResult GetProduct(string keywords)
        {
            var result = this.dbContextFactory.DbContext.Product.Select(m => new { m.ID, m.Name }).ToList();

            return Json(new
            {
                content = result.Select(m => new ProductReferences
                {
                    ID=m.ID,
                    Name=m.Name,
                    JsonInfo = JsonHelper.ToBase64(new
                    {
                        m.ID,
                        m.Name
                    })
                }).ToList(),
                type = "success",
                code = 0
            });

        }


        [HttpGet]
        public IActionResult GetContactByCompanyID(int id)
        {
            var result = this.dbContextFactory.DbContext.RelatedCompanyContacts.Where(m => m.RelatedCompanyID == id).Select(m => new { m.ID, m.Contacts, Info = JsonHelper.ToBase64(new { ID = m.ID.ToString(), Name = m.Contacts }) }).ToList();

            return Json(new
            {
                Status=200,
                List= result
            });
        }


        [HttpGet]
        public IActionResult GetXmSelectPositions()
        {
            List<XmSelectNode> result = new List<XmSelectNode>();
            CacheHelper cacheHelper = new CacheHelper(_cache);
            var listDepartment = cacheHelper.GetDepartments();
            var positions = cacheHelper.GetPositions();

            List<Department> topDepartments = listDepartment.Where(m => m.ParentDepartmentID == 0).ToList();
            if (topDepartments.Count == 0) { return Json(result); }

            if (topDepartments.Count == 1 && positions.Where(m => m.DepartmentID == topDepartments[0].ID).Count() == 0)//顶级节点只有一个，并且下面没有人
            {
                topDepartments = listDepartment.Where(m => m.ParentDepartmentID == topDepartments[0].ID).ToList();
            }
            foreach (var item in topDepartments)
            {
                XmSelectNode selectList = new XmSelectNode();
                selectList.value = item.ID.ToString();
                selectList.name = item.Name;
                //selectList.disabled = false;
                selectList.children = GetChildren(item.ID, listDepartment, positions, 0);
                result.Add(selectList);
            }
            return View(result);
        }
        public List<XmSelectNode> GetChildren(int departmentID, List<Department> departmentList, List<Position> listPosition, int index)
        {
            List<XmSelectNode> result = new List<XmSelectNode>();
            var departments = departmentList.Where(m => m.ParentDepartmentID == departmentID).ToList();
            var positions = listPosition.Where(m => m.DepartmentID == departmentID).ToList();
            foreach (var position in positions)
            {
                XmSelectNode selectList = new XmSelectNode();
                selectList.value = position.ID.ToString();
                selectList.name = position.Name;
                selectList.children = null;
                result.Add(selectList);
            }
            foreach (var item in departments)
            {
                XmSelectNode selectList = new XmSelectNode();
                selectList.value = item.ID.ToString();
                selectList.name = item.Name;

                selectList.children = GetChildren(item.ID, departmentList, listPosition, index);
                result.Add(selectList);
            }
            return result;

        }

        [HttpGet]
        public IActionResult GetXmSelectEmployees()
        {
            List<XmSelectNode> result = new List<XmSelectNode>();
            CacheHelper cacheHelper = new CacheHelper(_cache);
            var listDepartment = cacheHelper.GetDepartments();
            var eps = cacheHelper.GetVEmployeePositions();

            List<Department> topDepartments = listDepartment.Where(m => m.ParentDepartmentID == 0).ToList();
            if (topDepartments.Count == 0) { return Json(result); }

            if (topDepartments.Count == 1 && eps.Where(m => m.DepartmentID == topDepartments[0].ID).Count() == 0)//顶级节点只有一个，并且下面没有人
            {
                topDepartments = listDepartment.Where(m => m.ParentDepartmentID == topDepartments[0].ID).ToList();
            }
            foreach (var item in topDepartments)
            {
                XmSelectNode selectList = new XmSelectNode();
                selectList.value = item.ID.ToString();
                selectList.name = item.Name;
                selectList.children = GetEmployeeChildren(item.ID, listDepartment, eps, 0);
                result.Add(selectList);
            }
            return View(result);
        }
        public List<XmSelectNode> GetEmployeeChildren(int departmentID, List<Department> departmentList, List<VEmployeePosition> eps, int index)
        {
            List<XmSelectNode> result = new List<XmSelectNode>();
            var departments = departmentList.Where(m => m.ParentDepartmentID == departmentID).ToList();
            var currentEps = eps.Where(m => m.DepartmentID == departmentID).ToList();
            foreach (var ep in currentEps)
            {
                XmSelectNode selectList = new XmSelectNode();
                selectList.value = ep.EmpID;
                selectList.name = ep.EmpName;
                selectList.children = null;
                result.Add(selectList);
            }
            foreach (var item in departments)
            {
                XmSelectNode selectList = new XmSelectNode();
                selectList.value = "-" + item.ID.ToString();
                selectList.name = item.Name;
                selectList.children = GetEmployeeChildren(item.ID, departmentList, eps, index);
                result.Add(selectList);
            }
            return result;

        }


        [HttpGet]
        public IActionResult GetXmSelectDepartment()
        {
            List<XmSelectNode> result = new List<XmSelectNode>();
            CacheHelper cacheHelper = new CacheHelper(_cache);
            var listDepartment = cacheHelper.GetDepartments();
            var positions = cacheHelper.GetPositions();

            List<Department> topDepartments = listDepartment.Where(m => m.ParentDepartmentID == 0).ToList();
            if (topDepartments.Count == 0) { return Json(result); }

            if (topDepartments.Count == 1 && positions.Where(m => m.DepartmentID == topDepartments[0].ID).Count() == 0)//顶级节点只有一个，并且下面没有人
            {
                topDepartments = listDepartment.Where(m => m.ParentDepartmentID == topDepartments[0].ID).ToList();
            }
            foreach (var item in topDepartments)
            {
                XmSelectNode selectList = new ();
                selectList.value = item.ID.ToString();
                selectList.name = item.Name;
                selectList.children = GetDepartmentChildren(item.ID, listDepartment, positions, 0);
                result.Add(selectList);
            }
            return View(result);
        }

        public List<XmSelectNode> GetDepartmentChildren(int departmentID, List<Department> departmentList, List<Position> listPosition, int index)
        {
            List<XmSelectNode> result = new List<XmSelectNode>();
            var departments = departmentList.Where(m => m.ParentDepartmentID == departmentID).ToList();
            var positions = listPosition.Where(m => m.DepartmentID == departmentID).ToList();
             
            foreach (var item in departments)
            {
                XmSelectNode selectList = new XmSelectNode();
                selectList.value = item.ID.ToString();
                selectList.name = item.Name;
                selectList.children = GetDepartmentChildren(item.ID, departmentList, listPosition, index);
                result.Add(selectList);
            }
            return result;

        }


    }


    
   
}